<?php


namespace App\Bx;


use App\Core\Ioc;
use App\Job\QueueContract;
use App\Utils\Cache;
use App\Worker\Worker;
use Goutte\Client;

class BxStarter
{
    protected $topic;

    public function __construct()
    {
        $this->topic = new BxTopic();
    }

    const LAST_PAGE = 'BX_LAST_PAGE';
    protected $host = 'http://8xxka.com';
    protected $url = '/html/category/video/video4/';

    public function start(Ioc $ioc)
    {
//        $queue = $ioc->make(QueueContract::class);
//        $job = $queue->dequeue($this->topic->name);
//        $job->handle();
//        (new BxCrawlJob(sprintf('%s%s/page_%d.html', $this->host, $this->url, 5), $this->topic))->handle();
//        die();
        /**
         * @var Client $request
         */
        $request = $ioc->make('request');
        $crawler = $request->request('GET', $this->host.$this->url);
        $last = $crawler->filter('a.pagenum')->last()->attr('href');
        preg_match('/(\d+)/', $last,$last_pages);
        $last_page = (int)$last_pages[0];
        $old_last_page = (int)Cache::get(self::LAST_PAGE);
        $start_page = 1;
        if ($old_last_page) {
            $start_page = $last_page - $old_last_page;
        }
        for ($i = $start_page;$i<$last_page;$i++) {
            dispatch(new BxCrawlJob(sprintf('%s%s/page_%d.html', $this->host, $this->url, $i), $this->topic))
                ->onQueue($this->topic->name);
        }
        Cache::set(self::LAST_PAGE, $last_page);

        (new Worker($ioc, $this->topic))->start();
    }
}